/**
 * 代码文件格式化
 *
 * 需要安装以下依赖:
 * npm install prettier
 */

const fs = require('fs');
const path = require('path');
const prettier = require('prettier');
const toolsNode = require('../libs/tools-node');

// 获取传递给脚本的参数（排除前两个默认参数）
const args = process.argv.slice(2);
let from = args[0];
let toDirRoot = path.dirname(from);
let toName = path.basename(from);
toName = toName.replace(/^compress_/i, '');
let to = path.join(toDirRoot, `format_${toName}`);

async function formatFile(inputPath, outputPath) {
  try {
    let fileContent = fs.readFileSync(inputPath, 'utf8');
    // 获取 Prettier 配置（从 .prettierrc 等文件加载）
    let options = await prettier.resolveConfig(inputPath);
    // 格式化代码
    let formattedCode = await prettier.format(fileContent, {
      ...options,
      filepath: inputPath, // 自动推断语言
    });
    // 写入新文件
    toolsNode.writeFileSync(outputPath, formattedCode);
  } catch (error) {
    console.error('格式化过程中出错:', error);
    process.exit(1);
  }
}

formatFile(from, to);
